import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo/http/api.dart';
import 'package:flutter_demo/other/application.dart';
import 'package:flutter_demo/widget/tiny_widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:universal_html/html.dart' as html;

class SeeApplyScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SeeApplyScreenState();
}

class _SeeApplyScreenState extends State<SeeApplyScreen> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<List>(
          future: loadData(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                return Text("${snapshot.error}");
              } else {
                return screen(context, snapshot.data!);
              }
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }

  Widget screen(BuildContext context, List data) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          width: double.infinity,
          height: 60,
          padding: EdgeInsets.symmetric(
            horizontal: 195,
          ),
          decoration: BoxDecoration(
            color: Color(0xff1a56a8),
          ),
          child: Container(
            width: 580,
            height: 59,
            alignment: Alignment.centerLeft,
            child: Image(
              image: NetworkImage('http://my.gxrczc.com/assets/img/logo_zc.png'),
            ),
          ),
        ),
        Expanded(
          child: Container(
            width: double.infinity,
            height: double.infinity,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(
              vertical: 16,
              horizontal: 64,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            child: ListView(
              children: [
                for (int i = 0; i < data.length; i++) ...[
                  content(context, data[i]),
                  C(16),
                ]
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget content(BuildContext context, dynamic map) {
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Color(0xffe4f0ff),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Container(
        width: double.infinity,
        height: 130,
        alignment: Alignment.topLeft,
        child: Wrap(
          direction: Axis.vertical,
          spacing: 10,
          runSpacing: 74,
          children: map.entries.map<Widget>((entry) {
            var value = entry.value;
            if (entry.key.contains('申报日期')) {
              var date = DateTime.fromMillisecondsSinceEpoch(int.parse(entry.value));
              value = '${date.year}年${date.month}月${date.day}日';
            }
            return item(context, entry.key, value);
          }).toList(),
        ),
      ),
    );
  }

  Widget item(BuildContext context, String title, dynamic data) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          child: Text(
            '$title :',
            style: TextStyle(
              color: Color(0xff333333),
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        C(8),
        Container(
          child: title.contains('申报附件')
          ? InkWell(
            onTap: () => downloadFile(title, data),
            child: Text(
              '点击下载$title',
              style: TextStyle(
                color: Colors.blue,
                fontSize: 16,
              ),
            ),
          )
          : Text(
            data == null ? '' : data.toString(),
            style: TextStyle(
              color: Color(0xff333333),
              fontSize: 16,
            ),
          ),
        ),
      ],
    );
  }

  void downloadFile(String title, String data) {
    final anchor = html.document.createElement('a') as html.AnchorElement
      ..href = SystemApi.downloadUrl + data
      ..style.display = 'none'
      ..download = '$title.${data.split('.').last}';
    html.document.body!.children.add(anchor);
    anchor.click();
  }

  Future<List> loadData() async {
    Response response = await SystemApi.see_apply(Application.currentAccount);
    if (response.statusCode == 200) {
      return json.decode(response.data);
    } else {
      Fluttertoast.showToast(msg: response.statusCode.toString());
      return Future.error('状态码: ${response.statusCode.toString()}');
    }
  }
}